<template>
  <!-- 添加容器类名 -->
  <div class="content-card task-hall-container">
    <div class="header-section">
      <h2 class="module-title">接单大厅</h2>
      <!-- 发布任务按钮 -->
      <el-button type="primary" @click="showPublishDialog = true" class="publish-btn">
        <el-icon><Plus /></el-icon>
        发布任务
      </el-button>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-bar">
      <!-- 重构搜索框容器 -->
      <div class="search-container">
        <el-input
          v-model="searchText"
          placeholder="搜索任务/发布者..."
          class="task-search-input"
          @keyup.enter="handleSearch"
          prefix-icon=""
          suffix-icon=""
        ></el-input>
        <el-icon class="search-icon" @click="handleSearch">
          <Search />
        </el-icon>
      </div>

      <!-- 筛选下拉框组 -->
      <div class="filter-group">
        <el-select v-model="taskType" placeholder="任务类型" class="filter-select" @change="filterTasks">
          <el-option label="全部" value=""></el-option>
          <el-option label="学习帮助" value="学习帮助"></el-option>
          <el-option label="生活服务" value="生活服务"></el-option>
          <el-option label="技术支持" value="技术支持"></el-option>
          <el-option label="代购服务" value="代购服务"></el-option>
          <el-option label="其他" value="其他"></el-option>
        </el-select>
        <el-select v-model="priceRange" placeholder="价格范围" class="filter-select" @change="filterTasks">
          <el-option label="全部" value=""></el-option>
          <el-option label="0-20元" value="0-20"></el-option>
          <el-option label="20-50元" value="20-50"></el-option>
          <el-option label="50-100元" value="50-100"></el-option>
          <el-option label="100元以上" value="100+"></el-option>
        </el-select>
        <el-select v-model="sortBy" placeholder="排序方式" class="filter-select" @change="sortTasks">
          <el-option label="最新发布" value="time"></el-option>
          <el-option label="价格从低到高" value="price_asc"></el-option>
          <el-option label="价格从高到低" value="price_desc"></el-option>
        </el-select>
      </div>
    </div>



    <!-- 任务列表 -->
    <div class="task-grid" v-loading="loading">
      <div class="task-card" v-for="task in filteredTasks" :key="task.id">
        <div class="task-header">
          <h3 class="task-title">{{ task.title }}</h3>
          <span class="task-price">¥{{ task.price }}</span>
        </div>
        <div class="task-content">
          <p class="task-desc">{{ task.description || '暂无描述' }}</p>
          <div class="task-meta">
            <span class="meta-item">
              <el-icon class="meta-icon"><Clock /></el-icon> 
              {{ formatDate(task.requiredTime) }}
            </span>
            <span class="meta-item countdown" :class="getCountdownClass(task.requiredTime)">
              <el-icon class="meta-icon"><Timer /></el-icon> 
              {{ getCountdown(task.requiredTime) }}
            </span>
            <div class="meta-item publisher-info" @click="goToUserProfile(task.publisherId)">
              <img class="publisher-avatar" :src="task.publisherAvatar || '/images/default-avatar.png'" :alt="task.publisherName" @error="$event.target.src='/images/default-avatar.png'" />
              <span class="publisher-name">{{ task.publisherName || '未知用户' }}</span>
            </div>
          </div>
        </div>
        <div class="task-footer">
          <el-tag size="small" class="task-tag">{{ task.category }}</el-tag>
          <el-button 
            type="primary" 
            size="small" 
            :class="['accept-btn', { 'expired': isTaskExpired(task.requiredTime) }]"
            @click="acceptTask(task.id)"
            :disabled="task.status !== 'OPEN' || isTaskExpired(task.requiredTime)"
          >
            {{ getTaskButtonText(task) }}
          </el-button>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="!loading && filteredTasks.length === 0" class="empty-state">
        <el-empty description="暂无任务订单" />
      </div>
    </div>

    <!-- 发布任务对话框 -->
    <el-dialog 
      v-model="showPublishDialog" 
      title="发布任务" 
      width="600px"
      :before-close="handleCloseDialog"
      class="publish-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      center
    >
      <el-form 
        :model="taskForm" 
        :rules="taskRules" 
        ref="taskFormRef" 
        label-width="100px"
      >
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="taskForm.title" placeholder="请输入任务标题" maxlength="100" show-word-limit />
        </el-form-item>
        
        <el-form-item label="任务分类" prop="category">
          <el-select v-model="taskForm.category" placeholder="请选择任务分类" style="width: 100%">
            <el-option label="学习帮助" value="学习帮助" />
            <el-option label="生活服务" value="生活服务" />
            <el-option label="技术支持" value="技术支持" />
            <el-option label="代购服务" value="代购服务" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="任务金额" prop="price">
          <el-input-number 
            v-model="taskForm.price" 
            :min="1" 
            :max="9999" 
            :precision="2" 
            placeholder="请输入任务金额"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="完成时间" prop="requiredTime">
          <el-date-picker
            v-model="taskForm.requiredTime"
            type="datetime"
            placeholder="请选择要求完成时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        
        <el-form-item label="具体要求" prop="description">
          <el-input 
            v-model="taskForm.description" 
            type="textarea" 
            :rows="4" 
            placeholder="请详细描述任务要求和完成标准"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="submitTask" :loading="submitting">
            发布任务
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue';
import { Search, Clock, User, Plus, Timer } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from '@/utils/axiosConfig';
import { useRouter } from 'vue-router';

// 路由实例
const router = useRouter();

// 数据状态
const loading = ref(false);
const submitting = ref(false);
const tasks = ref([]);
const showPublishDialog = ref(false);
const taskFormRef = ref();

// 搜索和筛选
const searchText = ref('');
const taskType = ref('');
const priceRange = ref('');
const sortBy = ref('time');

// 任务表单
const taskForm = reactive({
  title: '',
  category: '',
  price: null,
  requiredTime: '',
  description: '',
  publisherId: 1 // 临时使用固定用户ID，实际应从登录状态获取
});

// 表单验证规则
const taskRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择任务分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入任务金额', trigger: 'blur' },
    { type: 'number', min: 1, message: '金额必须大于0', trigger: 'blur' }
  ],
  requiredTime: [
    { required: true, message: '请选择完成时间', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入具体要求', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
  ]
};

// 计算属性：过滤后的任务列表
const filteredTasks = computed(() => {
  let result = [...tasks.value];
  
  // 搜索过滤
  if (searchText.value) {
    const keyword = searchText.value.toLowerCase();
    result = result.filter(task => 
      task.title.toLowerCase().includes(keyword) ||
      (task.description && task.description.toLowerCase().includes(keyword)) ||
      (task.publisherName && task.publisherName.toLowerCase().includes(keyword))
    );
  }
  
  // 分类过滤
  if (taskType.value) {
    result = result.filter(task => task.category === taskType.value);
  }
  
  // 价格范围过滤
  if (priceRange.value) {
    if (priceRange.value.includes('+')) {
      // 处理 "100+" 这种格式
      const min = parseInt(priceRange.value.replace('+', ''));
      result = result.filter(task => {
        const price = parseFloat(task.price);
        const isValid = !isNaN(price) && price >= min;
        return isValid;
      });
    } else {
      // 处理 "20-50" 这种格式
      const [min, max] = priceRange.value.split('-');
      result = result.filter(task => {
        const price = parseFloat(task.price);
        const isValid = !isNaN(price) && price >= parseInt(min) && price <= parseInt(max);
        return isValid;
      });
    }
  }
  
  // 排序
  if (sortBy.value === 'price_asc') {
    result.sort((a, b) => a.price - b.price);
  } else if (sortBy.value === 'price_desc') {
    result.sort((a, b) => b.price - a.price);
  } else {
    result.sort((a, b) => new Date(b.createdTime) - new Date(a.createdTime));
  }
  
  return result;
});

// 获取用户信息
const getUserInfo = async (userId) => {
  try {
    const response = await axios.get(`/auth/user/${userId}`);
    if (response.data.success) {
      return response.data.user;
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
  return null;
};

// 获取任务列表
const fetchTasks = async () => {
  loading.value = true;
  try {
    const response = await axios.get('/task-orders/status/OPEN');
    if (response.data.success) {
      const taskList = response.data.data || [];
      
      // 为每个任务获取发布者信息
      for (const task of taskList) {
        if (task.publisherId) {
          const userInfo = await getUserInfo(task.publisherId);
          if (userInfo) {
            task.publisherName = userInfo.username;
            task.publisherAvatar = userInfo.avatar;
          }
        }
      }
      
      tasks.value = taskList;
    } else {
      ElMessage.error('获取任务列表失败');
    }
  } catch (error) {
    console.error('获取任务列表失败:', error);
    ElMessage.error('获取任务列表失败');
  } finally {
    loading.value = false;
  }
};

// 跳转到用户资料页面
const goToUserProfile = async (userId) => {
  if (!userId) {
    ElMessage.warning('用户信息不完整');
    return;
  }
  try {
    // 跳转到用户主页，传递用户ID参数
    await router.push({
      name: 'UserProfile',
      params: { userId: userId }
    });
  } catch (error) {
    console.error('跳转用户主页失败:', error);
    ElMessage.error('跳转失败，请重试');
  }
};

// 搜索功能
const handleSearch = () => {
  // 搜索逻辑已在计算属性中实现
};

// 筛选功能
const filterTasks = () => {
  // 筛选逻辑已在计算属性中实现
};

// 排序功能
const sortTasks = () => {
  // 排序逻辑已在计算属性中实现
};

// 获取当前用户ID
const getCurrentUserId = () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return null;
    }
    // 解析JWT token获取用户ID
    const payload = JSON.parse(atob(token.split('.')[1]));
    // JWT的subject字段存储的是用户ID
    return payload.sub ? parseInt(payload.sub) : null;
  } catch (error) {
    console.error('解析token失败:', error);
    return null;
  }
};

// 接单功能
const acceptTask = async (taskId) => {
  try {
    // 检查用户是否已登录
    const currentUserId = getCurrentUserId();
    if (!currentUserId) {
      ElMessage.error('请先登录');
      return;
    }
    
    await ElMessageBox.confirm('确定要接受这个任务吗？', '确认接单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const requestData = {
      accepterId: currentUserId
    };
    

    
    const response = await axios.post(`/task-orders/${taskId}/accept`, requestData);
    
    if (response.data.success) {
      ElMessage.success('接单成功！');
      fetchTasks(); // 刷新任务列表
    } else {
      ElMessage.error(response.data.message || '接单失败');
    }
  } catch (error) {
    if (error !== 'cancel') {

      const errorMessage = error.response?.data?.message || '接单失败';
      ElMessage.error(errorMessage);
    }
  }
};

// 提交任务
const submitTask = async () => {
  if (!taskFormRef.value) return;
  
  try {
    // 检查用户是否已登录
    const currentUserId = getCurrentUserId();
    if (!currentUserId) {
      ElMessage.error('请先登录');
      return;
    }
    
    await taskFormRef.value.validate();
    
    // 设置发布者ID为当前用户ID
    taskForm.publisherId = currentUserId;
    
    submitting.value = true;
    const response = await axios.post('/task-orders', taskForm);
    
    if (response.data.success) {
      ElMessage.success('任务发布成功！');
      showPublishDialog.value = false;
      resetForm();
      fetchTasks(); // 刷新任务列表
    } else {
      ElMessage.error(response.data.message || '发布失败');
    }
  } catch (error) {
    console.error('发布任务失败:', error);
    ElMessage.error('发布任务失败');
  } finally {
    submitting.value = false;
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(taskForm, {
    title: '',
    category: '',
    price: null,
    requiredTime: '',
    description: '',
    publisherId: null // 将在提交时设置为当前用户ID
  });
  if (taskFormRef.value) {
    taskFormRef.value.resetFields();
  }
};

// 关闭对话框
const handleCloseDialog = () => {
  showPublishDialog.value = false;
  resetForm();
};

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7; // 禁用昨天之前的日期
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 计算倒计时
const getCountdown = (requiredTime) => {
  if (!requiredTime) return '时间未设置';
  
  const now = new Date();
  const deadline = new Date(requiredTime);
  const diffMs = deadline.getTime() - now.getTime();
  
  if (diffMs <= 0) {
    return '已截止';
  }
  
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  const diffHours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
  
  if (diffDays > 0) {
    return `${diffDays}天${diffHours}小时`;
  } else if (diffHours > 0) {
    return `${diffHours}小时${diffMinutes}分钟`;
  } else {
    return `${diffMinutes}分钟`;
  }
};

// 获取倒计时样式类
const getCountdownClass = (requiredTime) => {
  if (!requiredTime) return '';
  
  const now = new Date();
  const deadline = new Date(requiredTime);
  const diffMs = deadline.getTime() - now.getTime();
  const diffHours = diffMs / (1000 * 60 * 60);
  
  if (diffMs <= 0) {
    return 'expired';
  } else if (diffHours <= 2) {
    return 'urgent';
  } else if (diffHours <= 24) {
    return 'warning';
  } else {
    return 'normal';
  }
};

// 检查任务是否已截止
const isTaskExpired = (requiredTime) => {
  if (!requiredTime) return false;
  const now = new Date();
  const deadline = new Date(requiredTime);
  return deadline.getTime() <= now.getTime();
};

// 获取任务按钮文本
const getTaskButtonText = (task) => {
  if (task.status !== 'OPEN') {
    return '已接单';
  }
  if (isTaskExpired(task.requiredTime)) {
    return '已截止';
  }
  return '接单';
};

// 定时器引用
const countdownTimer = ref(null);

// 组件挂载时获取数据并启动定时器
onMounted(() => {
  fetchTasks();
  // 每分钟更新一次倒计时
  countdownTimer.value = setInterval(() => {
    // 触发响应式更新
    tasks.value = [...tasks.value];
  }, 60000);
});

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
});
</script>

<style scoped>
/* 头部区域样式 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.module-title {
  margin: 0;
  color: #303133;
}

.publish-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.search-filter-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f8fafc;
  border-radius: 8px;
}

/* 重构搜索容器样式 */
.search-container {
  position: relative;
  flex: 1;
  min-width: 200px;
}

.task-search-input {
  --el-input-height: 40px;
  width: 100%;
  padding-right: 40px !important;
}

/* 搜索图标精确位置 */
.search-icon {
  position: absolute !important;
  right: 12px !important;
  top: 50% !important;
  transform: translateY(-50%) !important;
  width: 18px !important;
  height: 18px !important;
  color: #606266 !important;
  cursor: pointer !important;
  z-index: 999 !important;
  background: transparent !important;
}

.search-icon:hover {
  color: #409eff !important;
}

/* 筛选框样式 */
.filter-group {
  display: flex;
  gap: 12px;
}

.filter-select {
  width: 140px;
  --el-select-input-height: 40px;
}

/* 强制隐藏筛选框箭头 */
:deep(.filter-select .el-select__caret) {
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1) !important;
}

:deep(.filter-select .el-select:focus-within .el-select__caret) {
  opacity: 0 !important;
  width: 0 !important;
  height: 0 !important;
  margin-left: -8px !important;
  pointer-events: none !important;
}

/* 备用方案：直接针对Element Plus的CSS变量 */
:deep(.filter-select .el-select:focus-within) {
  --el-select-caret-color: transparent !important;
}

/* 任务列表样式 */
.task-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.task-card {
  border: none;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s, box-shadow 0.2s;
}

.task-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.task-title {
  font-size: 16px;
  margin: 0 0 10px 0;
  color: #1f2937;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.task-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

/* 发布者信息样式 */
.publisher-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.2s;
  padding: 4px 8px;
  border-radius: 4px;
}

.publisher-info:hover {
  background-color: #f0f9ff;
  color: #409eff;
}

.publisher-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #e5e7eb;
}

.publisher-name {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.publisher-info:hover .publisher-name {
  color: #409eff;
}

.task-desc {
  color: #4b5563;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 15px;
}

.task-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-icon {
  width: 16px;
  height: 16px;
  margin-right: 5px;
  vertical-align: middle;
  color: #909399;
}

/* 倒计时样式 */
.countdown {
  font-weight: 500;
}

.countdown.normal {
  color: #67c23a;
}

.countdown.warning {
  color: #e6a23c;
}

.countdown.urgent {
  color: #f56c6c;
  animation: pulse 1.5s infinite;
}

.countdown.expired {
  color: #909399;
  text-decoration: line-through;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
  100% {
    opacity: 1;
  }
}

.task-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.task-tag {
  background-color: #ecfdf5;
  color: #059669;
}

.accept-btn {
  width: auto;
  padding: 6px 15px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-options {
    flex-direction: column;
  }
  .filter-select {
    width: 100%;
  }
  .task-grid {
    grid-template-columns: 1fr;
  }
}

/* 修复输入框内边距 */
:deep(.el-input__wrapper) {
  padding-right: 40px !important;
}

/* 空状态样式 */
.empty-state {
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 发布任务对话框响应式样式 */
:deep(.publish-dialog) {
  max-width: 90vw;
  margin: 0 auto;
}

:deep(.publish-dialog .el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

@media (max-width: 768px) {
  :deep(.publish-dialog) {
    width: 95vw !important;
    margin: 0;
  }
  
  :deep(.publish-dialog .el-dialog__body) {
    padding: 15px;
    max-height: 60vh;
  }
  
  :deep(.publish-dialog .el-form-item__label) {
    width: 80px !important;
    font-size: 14px;
  }
  
  :deep(.publish-dialog .el-form-item__content) {
    margin-left: 80px !important;
  }
}

@media (max-width: 480px) {
  :deep(.publish-dialog) {
    width: 100vw !important;
    height: 100vh !important;
    margin: 0;
    border-radius: 0;
  }
  
  :deep(.publish-dialog .el-dialog__header) {
    padding: 15px 20px;
  }
  
  :deep(.publish-dialog .el-dialog__body) {
    padding: 10px 20px;
    max-height: calc(100vh - 120px);
  }
  
  :deep(.publish-dialog .el-form-item) {
    margin-bottom: 15px;
  }
  
  :deep(.publish-dialog .el-form-item__label) {
    width: 70px !important;
    font-size: 13px;
  }
  
  :deep(.publish-dialog .el-form-item__content) {
    margin-left: 70px !important;
  }
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}

/* 任务卡片状态样式 */
.task-card .accept-btn:disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
}

/* 已截止任务按钮样式 */
.task-card .accept-btn:disabled.expired {
  background-color: #fef0f0;
  border-color: #fbc4c4;
  color: #f56c6c;
}

/* 任务操作按钮样式 */
.task-actions {
  margin-top: 10px;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-filter-bar {
    flex-direction: column;
    gap: 12px;
  }
  
  .filter-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .filter-select {
    width: 100%;
  }
}
</style>

<!-- 删除此行重复导入 -->
<style src="@/assets/styles/task-hall-global.css"></style>